package com.hjt.gulimall.product.service.impl;

import com.hjt.gulimall.product.entity.SkuImagesEntity;
import com.hjt.gulimall.product.entity.SkuSaleAttrValueEntity;
import com.hjt.gulimall.product.entity.SpuInfoDescEntity;
import com.hjt.gulimall.product.service.*;
import com.hjt.gulimall.product.vo.SkuItemVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hjt.common.utils.PageUtils;
import com.hjt.common.utils.Query;

import com.hjt.gulimall.product.dao.SkuInfoDao;
import com.hjt.gulimall.product.entity.SkuInfoEntity;
import org.springframework.util.StringUtils;
import rx.Completable;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {


    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    AttrGroupService attrGroupService;

    @Autowired
    ThreadPoolExecutor executor;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 条件分页查询sku信息
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {

        /**
         * sidx: 'id',//排序字段
         * order: 'asc/desc',//排序方式
         * key: '华为',//检索关键字
         * catelogId: 0,
         * brandId: 0,
         * min: 0,
         * max: 0
         */
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();

        // 封装查询条件
        // sku名字或id
        String key = (String) params.get("key");
        if (StringUtils.hasLength(key)) {
            wrapper.and(obj -> {
                obj.eq("sku_id",key).or().like("sku_name",key);
            });
        }
        // 分类
        String catelogId = (String) params.get("catelogId");
        if (StringUtils.hasLength(catelogId)) {
            try {
                if (Integer.parseInt(catelogId) > 0) {
                    wrapper.eq("catalog_id",catelogId);
                }
            }
            catch (NumberFormatException exception) {
                log.warn("分类id小于等于0,====>"+catelogId);
            }
        }
        // 品牌
        String brandId = (String) params.get("brandId");
        if (StringUtils.hasLength(brandId)) {
            try {
                if (Integer.parseInt(brandId) > 0) {
                    wrapper.eq("brand_id",brandId);
                }
            }
            catch (NumberFormatException exception) {
                log.warn("品牌id小于等于0,====>"+brandId);
            }
        }
        // 大于等于最小价格
        String min = (String) params.get("min");
        if (StringUtils.hasLength(min)) {
            wrapper.ge("price", min);
        }
        // 小于等于最大价格
        String max = (String) params.get("max");
        if (StringUtils.hasLength(max)) {
            wrapper.le("price", max);
        }
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }


    /**
     * 根据spuid查询对应的sku
     * @param spuId
     * @return
     */
    @Override
    public List<SkuInfoEntity> listBySpuId(Long spuId) {
        return baseMapper.selectList(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
    }

    @Override
    public SkuItemVo item(Long skuId) throws ExecutionException, InterruptedException {
        SkuItemVo skuItemVo = new SkuItemVo();

        CompletableFuture<SkuInfoEntity> skuInfoEntityFuture = CompletableFuture.supplyAsync(() -> {
            // 1.基本信息获取
            SkuInfoEntity skuInfoEntity = this.getById(skuId);
            skuItemVo.setInfo(skuInfoEntity);
            return skuInfoEntity;
        }, executor);

        CompletableFuture<Void> skuImageFuture = CompletableFuture.runAsync(() -> {
            // 2.sku图片信息
            List<SkuImagesEntity> skuImagesEntityList = skuImagesService.listBySkuId(skuId);
            skuItemVo.setImages(skuImagesEntityList);
        });

        CompletableFuture<Void> skuItemSaleAttrVoListFuture =  skuInfoEntityFuture.thenAcceptAsync((result) -> {
            Long spuId = result.getSpuId();
            // 3.spu销售属性信息
            List<SkuItemVo.SkuItemSaleAttrVo> skuItemSaleAttrVoList = skuSaleAttrValueService.listBySpuId(spuId);
            skuItemVo.setSaleAttrVos(skuItemSaleAttrVoList);
        }, executor);

        CompletableFuture<Void> attrGroupVosFuture = skuInfoEntityFuture.thenAcceptAsync((result) -> {
            // 4.spu规格参数信息
            List<SkuItemVo.SpuItemBaseGroupVo> attrGroupVos = attrGroupService.getAttrGroupWithAttrsBySpuIdAndCatalogId(result.getSpuId(), result.getCatalogId());
            skuItemVo.setAttrGroupVos(attrGroupVos);
        }, executor);

        CompletableFuture<Void> spuInfoDescEntityFuture = skuInfoEntityFuture.thenAcceptAsync((result) -> {
            // 5.spu商品介绍信息
            SpuInfoDescEntity spuInfoDescEntity = spuInfoDescService.getById(result.getSpuId());
            skuItemVo.setDescription(spuInfoDescEntity);
        }, executor);


        // 等到所有任务都完成
        CompletableFuture.allOf(skuImageFuture,skuItemSaleAttrVoListFuture,attrGroupVosFuture,spuInfoDescEntityFuture).get();


        // 6.sku库存信息
        return skuItemVo;
    }
}